package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"novel-world/model/cache"
	"novel-world/model/mysql"
	"strconv"

	"novel-world/novelrpc/internal/svc"
	"novel-world/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	user := &mysql.User{
		Mobile:   in.Mobile,
		Password: in.Password,
		Image:    "https://p1.ssl.qhimgs1.com/t040a4d781dd81e9eab.jpg",
		Title:    fmt.Sprintf("用户_%d", rand.Intn(100000)),
	}
	if err := user.LoginAdd(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if in.Password == "" {
		result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
		if result != in.SendSmsEnd {
			return nil, errors.New("验证码错误")
		}
	} else if in.Password != user.Password {
		return nil, errors.New("密码错误")
	}

	return &novelrpc.LoginResponse{
		Token: strconv.Itoa(int(user.ID)),
	}, nil
}
